<?php


namespace modules\english;


use constant\migrate\English;
use lib\exception\CliException;
use model\english\EnglishDb;
use modules\es\EnglishEs;

class WordsRead2Db
{

    public static function split()
    {
        $file = English::WORDS_SPLIT_FILE_PATH;

        $content = file_get_contents($file);

        $rows = explode("\n", $content);

        if (empty($rows)) throw new CliException('no row');

        $insertData = [];
        foreach ($rows as $row) {
            $row = trim($row);
            $fields = explode('|', $row);
            $word = $fields[0] ?? '';
            $split = $fields[1] ?? '';
            $explain = $fields[2] ?? '';
            $splitArr = explode('+', $split);
            $split_first = $splitArr[0] ?? '';
            $split_second = $splitArr[1] ?? '';
            $split_third = $splitArr[2] ?? '';
            $split_fourth = $splitArr[3] ?? '';
            $split_fifth = $splitArr[4] ?? '';
            $split_sixth = $splitArr[5] ?? '';
            $content = implode(' + ', $split) . ' ' . $explain;
            $insertData[] = compact('word', 'content', 'split_first', 'split_second', 'split_third', 'split_fourth', 'split_fifth', 'split_sixth');
        }

        var_dump($file);
    }

    /**
     * @param $fileName
     * @param string $style
     * @return false|string[]
     * @throws \Exception
     */
    public static function format($fileName, $style = 'info')
    {
        if (! file_exists($fileName)) throw new \Exception('file not found');
        $content = file_get_contents($fileName);

        $arr = explode("\n", $content);

        $signPattern = '/(?<=\[).+(?=\])/';
        $wordPattern = '/[a-z]\s\[/i';
        $wordReplacePattern = '/^\d+\./i';

        $words = [];
        foreach ($arr as $v) {
            $v = trim($v);
            if (strlen($v) == 0) continue;

            //单词
            $isWord = preg_match($wordPattern, $v);
            if ($isWord) {
                unset($eg);
                $eg = [];
                //分割单词
                $pos = strpos($v, '[');
                $header = mb_substr($v, 0, $pos);
                //替换序号
                $header = preg_replace($wordReplacePattern, '', $header);
                $word = trim($header);
                $words[] = [
                    'word' => $word,
                    'sign' => $sign ?? '',
                    'content' => $v,
                    'eg' => &$eg,
                ];
            } else {
                preg_match($signPattern, $v, $matches);
                $sign = current($matches);
                if ($sign) {
                    //标签匹配
                    unset($matches);
                } else {
                    //例句处理
                    $eg[] = $v;
                }
            }

        }
        return $words;
    }
}